﻿//#define SINGLE_INSTANCE_ONLY
using System;
using System.Threading;
using System.Windows.Forms;
using Oxage.Common;
using Oxage.Forms;

namespace Oxage
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Config.RegistryRootPath = AppConfig.RegistryRootPath;
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
			Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			StartProcess();
		}

		/// <summary>
		/// Starts the process, only single instance is allowed.
		/// </summary>
		static void StartProcess()
		{
#if SINGLE_INSTANCE_ONLY
			Mutex mt = null;
			try
			{
				mt = Mutex.OpenExisting(Application.ProductName);
			}
			catch
			{
			}

			//Allow only one application to be opened at the time
			if (mt == null)
			{
				mt = new Mutex(true, Application.ProductName);
				Application.Run(new MainForm());
				GC.KeepAlive(mt);
				mt.ReleaseMutex();
			}
			else
			{
				//Another application is already running, close the current one
				mt.Close();
				Application.Exit();
			}
#else
			Application.Run(new MainForm());
#endif
		}

		private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			Logger.Log(e.ExceptionObject as Exception, LogLevels.Crash);
		}

		private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
		{
			Logger.Log(e.Exception, LogLevels.Crash);
		}
	}
}
